package com.panda.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.panda.entity.po.LoginUser;
import com.panda.entity.po.User;
import com.panda.mapper.MenuMapper;
import com.panda.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service("userDetailsServiceImpl")
public class UserDetailsServiceImpl implements UserDetailsService {

    private final UserMapper userMapper;
    private final MenuMapper menuMapper;

    @Autowired
    public UserDetailsServiceImpl(UserMapper userMapper, MenuMapper menuMapper) {
        this.userMapper = userMapper;
        this.menuMapper = menuMapper;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {


        // 存储用户的权限
        List<String> list = new ArrayList<>();
        //根据用户名查询用户
        LambdaQueryWrapper<User> wrapper_user = new LambdaQueryWrapper<>();
        wrapper_user.eq(User::getUsername, username);
        User user = userMapper.selectOne(wrapper_user);
        //判断是否存在用户或是否拥有管理权限
        if (Objects.isNull(user) || user.getIsAdmin().equals("0")) {
            throw new RuntimeException("用户不存在");
        }

        System.out.println(user.getId());
        // 根据当前用户id查询user_role表查询管理员权限
        list = menuMapper.selectPermsByUserId(user.getId());
        //返回用户信息
        return new LoginUser(user,list);
    }
}